//
//  ViewController.m
//  URL
//
//  Created by apple on 15/8/31.
//  Copyright (c) 2015年 戴维营. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
{

    NSMutableData *responseData;
    NSInteger expectedLength;

}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    创建对应的URL
    NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/9d82d158ccbf6c81a6219bf6be3eb13533fa409d.jpg"];

//    创建对应的请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
//    创建NSURLConnection对象，并马上发送请求；
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    
    // Do any additional setup after loading the view, typically from a nib.
}

//判断是否响应；
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    
    if (httpResponse.statusCode == 200)
    {
        
        responseData = [NSMutableData data];
        expectedLength = httpResponse.expectedContentLength;
        
//        NSLog(@"%@",response);
    }
}

//响应数据；
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
    NSLog(@"下载进度：%.2f%%",responseData.length * 100.0 / expectedLength);
}

//下载完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%@", responseData);

    [responseData writeToFile:@"Users/apple/Desktop/abcde.jpg" atomically:YES];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
